package com.iss.wyy.proxy;

import java.lang.reflect.Method;

/**
 * 切面代理
 * 模板方法模式的切面类
 * 用户需要继承此方法，自己写before after逻辑
 */
public abstract class AspectProxy implements Proxy{
    @Override
    public final Object doProxy(ProxyChain proxyChain) throws Throwable {
       Object result =null;

       Class<?> cls = proxyChain.getTargetClass();
        Method method = proxyChain.getTargetMethod();
        Object[] params = proxyChain.getMethodParams();

        begin();
        try {
            if (intercept(cls, method, params)) {
                before(cls, method, params);
                result = proxyChain.doProxyChain();
                after(cls, method, params);
            } else {
                result = proxyChain.doProxyChain();
            }
        }catch (Exception e){
            e.printStackTrace();
            error(cls,method,params,e);
        }finally {
            end();
        }
        return result;
    }

    public void begin(){}

    public boolean intercept(Class<?> cls,Method method,Object[] params)throws Throwable {
        return true;
    }

    public void before (Class<?> cls,Method method,Object[] params)throws Throwable{

    }
    public void after (Class<?> cls,Method method,Object[] params)throws Throwable{

    }
    public void error (Class<?> cls,Method method,Object[] params,Throwable e)throws Throwable{

    }
    public void end(){}
}
